﻿using System;
using System.Reflection;

using BizElements.Core;
using PostSharp.Aspects;

using BizElements.BusinessLayer;

namespace BizElements.BusinessLayer.Aspects
{
    internal static class AopUtil
    {
        public static IActor GetActor(MethodExecutionArgs eventArgs)
        {
            object[] arguments = eventArgs.Arguments.ToArray() ?? new object[0];
            foreach (object arg in arguments)
            {
                if (arg is IActor)
                    return arg as IActor;
            }

            return null;
        }

        public static string GetTableName(AdviceArgs postsharpEventArgs)
        {
            if (postsharpEventArgs.Instance == null)
                return null;

            IEntity entity = postsharpEventArgs.Instance as IEntity;
            if (entity != null)
                return entity.Table.TableName;

            PropertyInfo tableProperty = postsharpEventArgs.Instance.GetType().GetProperty("Table");
            if (tableProperty != null && tableProperty.CanRead)
            {
                ParameterInfo[] indexParameters = tableProperty.GetIndexParameters();
                bool isNotIndexer = ArrayUtil.IsNullOrEmpty(indexParameters);
                if (isNotIndexer)
                {
                    IDbTable table = tableProperty.GetValue(postsharpEventArgs.Instance, null) as IDbTable;
                    if (table != null)
                        return table.TableName;
                }
            }

            return null;
        }
    }
}
